<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

// 清除任何可能的输出缓冲
ob_clean();

// 日志记录函数已禁用
// function writeLog($message) {}

try {
    // 日志已禁用
    // writeLog('MySQL连接测试开始');
    
    // 日志已禁用
    $requestMethod = $_SERVER['REQUEST_METHOD'] ?? 'UNKNOWN';
    // writeLog("请求方法: {$requestMethod}");
    
    if ($requestMethod !== 'POST') {
        // writeLog('错误: 请求方法不正确');
        echo json_encode(['success' => false, 'message' => '请求方法错误，当前方法: ' . $requestMethod]);
        exit;
    }

    $host = $_POST['host'] ?? '';
    $port = $_POST['port'] ?? '3306';
    $database = $_POST['database'] ?? '';
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    
    // 日志已禁用
    // writeLog("连接参数 - Host: {$host}, Port: {$port}, Database: {$database}, Username: {$username}");

    if (empty($host) || empty($database) || empty($username)) {
        // writeLog('错误: 缺少必要参数');
        echo json_encode([
            'success' => false, 
            'message' => '缺少必要参数',
            'debug' => [
                'host' => $host,
                'database' => $database,
                'username' => $username
            ]
        ]);
        exit;
    }

    $dsn = "mysql:host=$host;port=$port;dbname=$database;charset=utf8mb4";
    // writeLog("尝试连接数据库: {$dsn}");
    
    $startTime = microtime(true);
    $pdo = new PDO($dsn, $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_TIMEOUT => 5
    ]);
    $endTime = microtime(true);
    $duration = round(($endTime - $startTime) * 1000, 2);
    
    // writeLog("连接成功 - 耗时: {$duration}ms");
    echo json_encode(['success' => true, 'message' => '连接成功']);
} catch (PDOException $e) {
    $errorMsg = $e->getMessage();
    // writeLog("PDO连接错误: {$errorMsg}");
    echo json_encode(['success' => false, 'message' => $errorMsg]);
} catch (Exception $e) {
    $errorMsg = $e->getMessage();
    // writeLog("系统错误: {$errorMsg}");
    echo json_encode(['success' => false, 'message' => '系统错误: ' . $errorMsg]);
}
exit;
